package com.example.lib_common.widget.nine_pics

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * @author yaotianxue
 * @description 自定义分割线
 * @date 2025/2/12
 */
class SpaceItemDecoration(private val space:Int,private val spanCount:Int = 3):RecyclerView.ItemDecoration() {
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
       // super.getItemOffsets(outRect, view, parent, state)
        //下标
        //val position = parent.getChildLayoutPosition(view)
        val position = parent.getChildAdapterPosition(view)
        //总数
//        val itemCount = state.itemCount // 优先用 State 获取
//        if (itemCount == 1){
//            outRect.left = space
//            outRect.top = space
//            outRect.right = space
//            outRect.bottom = space
//            return
//        }
//        //默认间隔
//        outRect.left = space/2
//        outRect.top = space/2
//        outRect.right = space/2
//        outRect.bottom = space/2
//        //第一列
//        if(position % spanCount  == 0){
//            outRect.left = space
//        }
//        //最后一列
//        if(position % spanCount  == 2){
//            outRect.right = space
//        }
//        //第一行
//        if(position < spanCount ){
//            outRect.top = space
//        }
//        //最后一行  总数8 3行/  总数9 3行
//        val rows = itemCount / spanCount // 优先用 State 获取 / spanCount // 2
//        val lastRow = itemCount % spanCount// 2
//        if (lastRow == 0){
//            if(position >= spanCount*(rows-1)){
//                outRect.bottom = space
//            }
//        }else{
//            if(position >= spanCount*rows ){
//                outRect.bottom = space
//            }
//        }
        // 每个span分配的间隔大小
        val spanSpace = space * (spanCount + 1) / spanCount
        // 列索引
        val colIndex = position % spanCount
        //行索引
        val rowIndex = position / spanCount
        // 列左右空隙
        outRect.left = space * (colIndex + 1) - spanSpace * colIndex
        outRect.right = spanSpace * (colIndex + 1) - space * (colIndex + 1)
        //行上下空隙
        outRect.top = space * (rowIndex + 1) - spanSpace * rowIndex
        outRect.bottom = spanSpace * (rowIndex + 1) - space * (rowIndex + 1)
    }
}